package test.my.com.myapplicationtest.roll_number;


import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.support.annotation.ColorRes;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import test.my.com.myapplicationtest.R;

/**
 * Created by cooper on 2016/7/19 20:39.
 * 赚呗1.2.0之前版本数字滚动view。1.可以添加分隔符。2.可以自动进位。
 */
public class MultiScrollNumber extends LinearLayout {
    private Context mContext;
    private List<Integer> mTargetNumbers = new ArrayList<>();
    private List<Integer> mCurrentStartNumbers = new ArrayList<>();// 用来保存上一秒的数据
    private List<ScrollNumber> mScrollNumbers = new ArrayList<>();
    private float mTextSize;
    private int mTextColor;
//    private int mIntervalTime; // 间隔时间

    private int[] mTextColors = new int[]{R.color.red_E57337};
    private Interpolator mInterpolator = new AccelerateInterpolator();
    private String mFontFileName;

    private String decollator;//数字当中的分隔符，没有则为空
    private boolean isShowDecimalPoint;// 用于判断是否显示小数点

    public MultiScrollNumber(Context context) {
        this(context, null);
    }

    public MultiScrollNumber(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MultiScrollNumber(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;

        TypedArray typedArray = mContext.obtainStyledAttributes(attrs, R.styleable.MultiScrollNumber);
        mTextSize = typedArray.getDimension(R.styleable.MultiScrollNumber_numberSize, 30);
        mTextColor = typedArray.getColor(R.styleable.MultiScrollNumber_numberColor, Color.BLACK);
//        mIntervalTime = typedArray.getInteger(R.styleable.MultiScrollNumber_intervalTime, 100);
        typedArray.recycle();

        setOrientation(HORIZONTAL);
        setGravity(Gravity.CENTER);



    }

    public void resetView() {
        mTargetNumbers.clear();
        mScrollNumbers.clear();
        mCurrentStartNumbers.clear();
        removeAllViews();
    }

    /**
     * 设置动态数字
     * @param targetNum
     */
    public void setNumbers(String targetNum) {
        // 如果已经有数据了，把之前的数据添加到起始list中
        if (mTargetNumbers.size() > 0) {
            mCurrentStartNumbers.clear();
            for (int oldNum : mTargetNumbers) {
                mCurrentStartNumbers.add(oldNum);
            }
        }
        char[] toChars = targetNum.toCharArray();
        mTargetNumbers.clear();
        for (int i = toChars.length-1;i>=0;i--) {
            char num = toChars[i];
            mTargetNumbers.add(Integer.parseInt(num+""));
        }

        if (mScrollNumbers.size() != mTargetNumbers.size() ) {
            this.removeAllViews();
            mScrollNumbers.clear();
            if (TextUtils.isEmpty(decollator)) {
                addScrollNumber();
            } else {
                addScrollNumberWithDecollator();
            }
        } else if (mCurrentStartNumbers.size() < mTargetNumbers.size() && !TextUtils.isEmpty(decollator)) {// 处理当999到1000时，进位问题
            addScrollNumberWidthJinWei();
        } else {
            for (int i = 0; i < mScrollNumbers.size(); i++) {
                ScrollNumber scrollNumber = mScrollNumbers.get(i);
                scrollNumber.setNumber(mCurrentStartNumbers.get(i), mTargetNumbers.get(i));
            }
        }
    }

    /**
     * 添加ScrollNumber
     */
    private void addScrollNumber() {
        for (int i = 0; i < mTargetNumbers.size() ; i++) {
            ScrollNumber scrollNumber = new ScrollNumber(mContext);
            scrollNumber.setTextSize(mTextSize);
            scrollNumber.setTextColor(mTextColor);
            scrollNumber.setInterpolator(mInterpolator);
            if (!TextUtils.isEmpty(mFontFileName)) {
                scrollNumber.setTextFont(mFontFileName);
            }
            scrollNumber.setNumber(0, mTargetNumbers.get(i));
            mScrollNumbers.add(scrollNumber);
            addView(scrollNumber,0);
        }
        // 在前边添加小数点
        if (isShowDecimalPoint) {
            addDecimalPoint();
        }
    }

    /**
     * 添加ScrollNumber,并且添加分隔符。
     */
    private void addScrollNumberWithDecollator() {

        int posNum = 0;//记录添加view的position，用于添加分隔符
        for (int i = 0; i < mTargetNumbers.size() ; i++) {
            posNum++;
            ScrollNumber scrollNumber = new ScrollNumber(mContext);
            scrollNumber.setTextSize(mTextSize);
            scrollNumber.setTextColor(mTextColor);
            scrollNumber.setInterpolator(mInterpolator);
            if (!TextUtils.isEmpty(mFontFileName)) {
                scrollNumber.setTextFont(mFontFileName);
            }
            scrollNumber.setNumber(0, mTargetNumbers.get(i));
            mScrollNumbers.add(scrollNumber);
            addView(scrollNumber,0);
            if (posNum!=mTargetNumbers.size() && posNum % 3 == 0 ) {
                addDecollatorTv();
            }
        }
    }

    /**
     * 添加ScrollNumber,添加分隔符,并且处理数字进位，如999到1000。
     */
    private void addScrollNumberWidthJinWei() {
        this.removeAllViews();
        mScrollNumbers.clear();
        int posNum = 0;//记录添加view的position，用于添加分隔符
        for (int i = mCurrentStartNumbers.size()-1; i >=-1 ; i--) {//使用上一秒数据list
            posNum++;
            ScrollNumber scrollNumber = new ScrollNumber(mContext);
            scrollNumber.setTextSize(mTextSize);
            scrollNumber.setTextColor(mTextColor);
            scrollNumber.setInterpolator(mInterpolator);
            if (!TextUtils.isEmpty(mFontFileName)) {
                scrollNumber.setTextFont(mFontFileName);
            }
            if (i == -1) {// 在第一位添加新的位数
                scrollNumber.setNumber(0, mTargetNumbers.get(mCurrentStartNumbers.size()));
            } else {// 其他位还用上一秒的数据
                scrollNumber.setNumber(mCurrentStartNumbers.get(i), mTargetNumbers.get(i));
            }
            mScrollNumbers.add(scrollNumber);
            addView(scrollNumber,0);
            if (posNum!=mTargetNumbers.size() && posNum % 3 == 0 && !TextUtils.isEmpty(decollator)) {
                addDecollatorTv();
            }
        }
    }

    /**
     * 设置数字当中的分割符
     * @param decollator
     */
    public void setDecollator(String decollator) {
        this.decollator = decollator;
    }

    /**
     * 是否在数字前显示小数点
     * @param isShowDecimalPoint
     */
    public void showDecimalPoint(boolean isShowDecimalPoint) {
        this.isShowDecimalPoint = isShowDecimalPoint;
    }

    /**
     * 创建分隔符tv
     * @return
     */
    private void addDecollatorTv() {
        PunctuationTextView decimalPointTv = new PunctuationTextView(mContext);
        decimalPointTv.setPunctuationWithDouHao();
        decimalPointTv.setPunctuationColor(mTextColor);
        decimalPointTv.setPunctuationSize(mTextSize);
        addView(decimalPointTv,0);
    }

    /**
     * 创建小数点
     */
    private void addDecimalPoint() {
        PunctuationTextView decimalPointTv = new PunctuationTextView(mContext);
        decimalPointTv.setPunctuationWithJuHao();
        decimalPointTv.setPunctuationColor(mTextColor);
        decimalPointTv.setPunctuationSize(mTextSize);
        addView(decimalPointTv,0);
    }

    public void setTextColors(@ColorRes int[] textColors) {
        if (textColors == null || textColors.length == 0)
            throw new IllegalArgumentException("color array couldn't be empty!");
        mTextColors = textColors;
        for (int i = mScrollNumbers.size() - 1; i >= 0; i--) {
            ScrollNumber scrollNumber = mScrollNumbers.get(i);
            scrollNumber.setTextColor(ContextCompat
                    .getColor(mContext, mTextColors[i % mTextColors.length]));
        }
    }

    public void setMultiTextColor(int textColor) {
        this.mTextColor = textColor;
    }


    public void setTextSize(int textSize) {
        if (textSize <= 0) throw new IllegalArgumentException("text size must > 0!");
        mTextSize = textSize;
        for (ScrollNumber s : mScrollNumbers) {
            s.setTextSize(textSize);
        }
    }

    public void setInterpolator(Interpolator interpolator) {
        if (interpolator == null)
            throw new IllegalArgumentException("interpolator couldn't be null");
        mInterpolator = interpolator;
        for (ScrollNumber s : mScrollNumbers) {
            s.setInterpolator(interpolator);
        }
    }

    public void setTextFont(String fileName) {
        if (TextUtils.isEmpty(fileName)) throw new IllegalArgumentException("file name is null");
        mFontFileName = fileName;
        for (ScrollNumber s : mScrollNumbers) {
            s.setTextFont(fileName);
        }
    }

    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

}